package cn.lix.sc.elasticsearch.service;

import cn.lix.sc.elasticsearch.constants.EsNullValue;
import cn.lix.sc.elasticsearch.dto.Condition;
import cn.lix.sc.elasticsearch.dto.FirstTestDTO;
import cn.lix.sc.elasticsearch.utils.ESQueryHelper;
import cn.lix.sc.elasticsearch.utils.JacksonUtil;
import cn.lix.sc.elasticsearch.utils.TestUtils;
import cn.lix.sc.elasticsearch.utils.TransferConditions;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.action.support.replication.ReplicationResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class EsHandleService {

    private static final Logger log = LoggerFactory.getLogger(EsHandleService.class);

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @Autowired
    private BulkProcessor bulkProcessor;

    private static final String INDEX_NAME = "first_test";

    public Boolean existsIndex(String indexName){
        // 1. 创建一个get请求获取指定索引的信息
        GetIndexRequest getIndexRequest = new GetIndexRequest(indexName);

        // 2. 客户端执行请求判断索引是否存在
        try {
            return restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("查询es时异常，数据信息为", e);
            return null;
        }
    }

    /**
     * 异步单条新增
     */
    public void insertAsync(Integer id){
        IndexRequest indexRequest = new IndexRequest(INDEX_NAME);
        FirstTestDTO firstTest = TestUtils.createOne(id);
        indexRequest.source(JacksonUtil.toJSONString(firstTest), XContentType.JSON);
        indexRequest.timeout(TimeValue.timeValueSeconds(1));
        indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);
        //数据为存储而不是更新
        indexRequest.create(false);
        indexRequest.id(firstTest.getId());
        restHighLevelClient.indexAsync(indexRequest, RequestOptions.DEFAULT, new ActionListener<IndexResponse>() {
            @Override
            public void onResponse(IndexResponse indexResponse) {
                ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
                if (shardInfo.getFailed() > 0) {
                    for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
                        log.error("将id为：{}的数据存入ES时存在失败的分片，原因为：{}", indexRequest.id(), failure.getCause());
                    }
                }
            }
            @Override
            public void onFailure(Exception e) {
                log.error("{}:存储es时异常，数据信息为", indexRequest.id(), e);
            }
        });
    }

    /**
     * 同步单条新增
     */
    public void insert(Integer id){
        IndexRequest indexRequest = new IndexRequest(INDEX_NAME);
        FirstTestDTO firstTest = TestUtils.createOne(id);
        indexRequest.source(JacksonUtil.toJSONString(firstTest), XContentType.JSON);
        indexRequest.timeout(TimeValue.timeValueSeconds(1));
        indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);
        indexRequest.create(true);
        indexRequest.id(firstTest.getId());
        try {
            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("{}:存储es时异常，数据信息为", indexRequest.id(), e);
        }
    }

    /**
     * 批量新增
     */
    public void insertBatch(int startId, int size){
        List<FirstTestDTO> dto = TestUtils.createList(startId, size);
        Stream<IndexRequest> requestStream = dto.stream().map(e -> {
            IndexRequest request = new IndexRequest(INDEX_NAME);
            //填充id
            request.id(e.getId());
            //先不修改id
            request.source(JacksonUtil.toJSONString(e), XContentType.JSON);
            request.opType(DocWriteRequest.OpType.CREATE);
            return request;
           /* // 存在就更新
            UpdateRequest updateRequest = new UpdateRequest(INDEX_NAME, e.getId());
            updateRequest.doc(JacksonUtil.toJSONString(e), XContentType.JSON).upsert();
            return updateRequest;*/
        });
        requestStream.forEach(bulkProcessor::add);
        bulkProcessor.flush();
    }

    /**
     * 单挑更新
     */
    public void update(){

    }

    /**
     * 批量更新
     */
    public void updateBatch(){

    }
    /**
     * 删除一条
     */
    public Boolean deleteOne(String indexName, Integer deleteId){
        Boolean suceess = null;
        try {
            //删除请求
            DeleteRequest request = new DeleteRequest(indexName, String.valueOf(deleteId));
            //执行客户端请求
            DeleteResponse delete = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
            suceess = RestStatus.OK.equals(delete.status());
        } catch (IOException e) {
            e.printStackTrace();
            suceess = Boolean.FALSE;
        }
        log.info("索引为: {}, id为: {}删除数据【{}】",indexName, deleteId, suceess ? "成功" : "失败");
        return suceess;
    }

    /**
     * 根据条件删除
     */
    public void deleteByQuery(List<Condition> fields){
        DeleteByQueryRequest request = new DeleteByQueryRequest(INDEX_NAME);
        for (Condition field : fields) {

        }
        request.setQuery(ESQueryHelper.like("", ""));
        try {
            BulkByScrollResponse response = restHighLevelClient.deleteByQuery(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据条件删除
     */
    public List<?> search(List<Condition> fields){
        ESQueryHelper queryHelper = ESQueryHelper.build(INDEX_NAME);
        TransferConditions.transfer(fields, queryHelper);
        /*for (Condition field : fields) {
            queryHelper.and(ESQueryHelper.equals(field.getField(), field.getValue()));
        }*/
        try {
            SearchResponse execute = queryHelper.execute(restHighLevelClient);
            SearchHit[] hits = execute.getHits().getHits();
            if(hits != null && hits.length > 0){
                return Stream.of(hits).map(e -> {
                    Map<String, Object> sourceAsMap = e.getSourceAsMap();
                    sourceAsMap.entrySet().stream().forEach(entry -> {
                        Object entryValue = entry.getValue();
                        if(EsNullValue.nullValue(entryValue)){
                            entry.setValue(null);
                        }
                    });
                    return sourceAsMap;
                }).collect(Collectors.toList());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Collections.emptyList();
    }



}
